const { getHtml } = require('./utils/http')
const db = require('./utils/datebase')
const log = require('./utils/log')
const moment = require('moment')
let pageIndex = 0
let errCount = 0
let baseUrl = 'http://baiwanzy.com'
let config = {
    pageLimit: 10,
    delay: 100,
    isLimit: true
}
const getList = async (url, content) => {
    pageIndex++
    let $ = await getHtml(url, config.delay)
    if (pageIndex > config.pageLimit && config.isLimit) {
        log.i(`爬取完成`)
        pageIndex = 0
        return true
    }
    if (!$) {
        log.i('遇到错误：重启')
        if (errCount > 20) {
            log.i('错误超过10此，停止爬虫')
            return false
        }
        return getList(url, content)
    }
    let urls = []
    $('.xing_vb4 a').each((i, elem) => {
        urls.push(baseUrl + $(elem).attr('href'))
    })
    for (let i = 0; i < urls.length; i++) {
        await getDetail(urls[i], content)
    } 
    log.i(`第${pageIndex}页爬取完毕`)
    // 判断是否有下一页
    let next = ''
    $('div.pages .pagelink_a').each((i, elem) => {
        if ($(elem).text() == '下一页') {
            next = $(elem).attr('href')
        }
    })
    if (next) {
        return getList(baseUrl + next,content)
    } else {
        log.i('爬取完成')
        pageIndex = 0
        return true
    }
}
const getDetail = async (url, {base_type} ) => {
    let filmID = 0
    let $ = await getHtml(url, config.delay)
    if (!$) {
        log.i('遇到错误：跳过' + url)
        return
    }
    if ($('.vodh h2').text().indexOf('DVD') != -1)  {
        log.i('DVD版跳过')
        return
    }
    let info = $('.vodBox .vodInfo .vodinfobox ul li span')
    let film = {
        status: 1,
        pic:$('.vodImg img').attr('src'),
        name: $('.vodh h2').text().trim(),
        base_type,
        plot: $($('.ibox.playBox .vodplayinfo')[1]).text(),
        other_name: $(info[0]).text(),
        director: $(info[1]).text(),
        actors:$(info[2]).text(),
        year: $(info[6]).text(),
        updated_at: new Date()  
    }
    for(var key in film){ // 删除无效值
        if (!film[key]) {
            delete film[key]
        }
    }
    if (!film.name) {
        log.i('名称不存在：跳过' + url)
        return
    }
    if (film.director && film.director.length > 100) {
        film.director = '不详'
        return
    }
    let updated_at =  moment($(info[7]).text()).toDate()
    film.updated_at = updated_at
    // 类型
    $(info[3]).find('a').each((i, elem) => {
        film.content_type = film.content_type ? film.content_type : '' + $(elem).text() +','
    })
    let area_name = $(info[4]).text().trim();
    switch (area_name) {
        case '大陆':
            film.area_id=1
        break
        case '香港':
            film.area_id=2
        break
        case '台湾':
            film.area_id=3
        break
        case '美国':
            film.area_id=4
        break
        case '日本':
            film.area_id=5
        break
        case '韩国':
            film.area_id=6
        break
        case '泰国':
            film.area_id=7
        break
        case '新加坡':
            film.area_id=9
        break 
        case '英国':
            film.area_id=8
        break   
      
    }
    let exist = await db.existsAndGet('vods',{name: film.name, year: film.year})
    if (exist) {
        filmID  = exist['id']
        film.id = filmID
        await db.update('vods', film)
        log.i(`更新成功：`+ film.name)
    } else {
        film.created_at = film.updated_at
        filmID = await db.insert('vods', film)
        log.i(`插入成功：`+ film.name)
    }
    let elements =  $($('.vodplayinfo ul')[1]).find('li')
    let film_set = {
        type: 'm3u8',
        vod_id: filmID,
        group_id: 3,
        updated_at: new Date()
    }
    let urls = ''
    for (let i = 0; i<elements.length; i++) {
        let data = $(elements[i]).text().split('$')
        let name = data[0]
        let url = data[1]
        urls += `${name}$${url}\r\n`
    }
    film_set.urls = urls
    let existSet = await db.existsAndGet('play_sets', { vod_id: film_set.vod_id, group_id: film_set.group_id})
    if (existSet) {
        film_set.id = existSet.id
        await db.update('play_sets', film_set)
    } else {
        film_set.created_at = film_set.updated_at
        await db.insert('play_sets', film_set)
    }
    return
}
const start = async(param) => {
    config = param
    await getList('http://baiwanzy.com/?m=vod-type-id-1.html', {base_type: 'dianying'})
    await getList('http://baiwanzy.com/?m=vod-type-id-4.html', {base_type: 'dongman'})
    await getList('http://baiwanzy.com/?m=vod-type-id-3.html', {base_type: 'zongyi'})
    await getList('http://baiwanzy.com/?m=vod-type-id-2.html', {base_type: 'dianshiju'})
}
module.exports = {
    start
}